package com.netease.financial.module.authentication;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.netease.financial.R;
import com.netease.financial.common.security.SecurityJNI;
import com.netease.financial.common.util.EditTextUtils;
import com.netease.financial.common.util.NfsLog;
import com.netease.financial.common.util.PhoneNumberUtils;
import com.netease.financial.common.util.ToastUtils;
import com.netease.financial.common.util.ViewUtils;
import com.netease.financial.domain.Factory;
import com.netease.financial.internal.di.components.AuthenticationComponent;
import com.netease.financial.internal.di.components.DaggerAuthenticationComponent;
import com.netease.financial.internal.di.modules.AuthenticationModule;
import com.netease.financial.ui.activity.BaseAppCompatActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A login screen that offers login via email/passwordEditText.
 */
public class AuthenticationActivity extends BaseAppCompatActivity implements AuthenticationView {

    private static final String TAG = AuthenticationActivity.class.getSimpleName();

    private static final String INTENT_EXTRA_KEY_CLIENT_ID = "clientId";
    private static final String INTENT_EXTRA_KEY_HEAD_PORTRAIT_URL = "headPortraitUrl";
    private static final String INTENT_EXTRA_KEY_USER_ID = "userId";
    private static final String INTENT_EXTRA_KEY_NEXT_TIP = "nextTip";

//    @Bind(R.id.toolbar)
//    Toolbar toolbar;

    @Bind(R.id.loginProgress)
    ProgressBar loginProgress;

    @Bind(R.id.headPortrait)
    ImageView headPortrait;

    @Bind(R.id.clientId)
    TextView clientId;

    @Bind(R.id.passwordTitle)
    TextView passwordTitle;

    @Bind(R.id.passwordEditText)
    EditText passwordEditText;

    @Bind(R.id.passwordIndicator)
    ImageView passwordIndicator;

    @Bind(R.id.btnNext)
    Button btnNext;

    @Bind(R.id.logos)
    ImageView logos;

    @Bind(R.id.logoContainer)
    RelativeLayout logoContainer;

    private String mClientId;
    private String mHeadPortraitUrl;
    private String mUserId;
    private String mNextTip;
    private String mClientSecret;

    private boolean mClientSecretVisible = false;

    AuthenticationComponent authenticationComponent;

    @Inject
    AuthenticationPresenter authenticationPresenter;

    private class ClientId implements Factory<String> {

        @Override
        public String get() {
            return mClientId;
        }

    }

    private class ClientSecret implements Factory<String> {

        @Override
        public String get() {
            return mClientSecret;
        }

    }

    public static Intent getCallingIntent(Context context, String clientId, String headPortraitUrl, String userId) {
        Intent intent = new Intent(context, AuthenticationActivity.class);
        intent.putExtra(INTENT_EXTRA_KEY_CLIENT_ID, clientId);
        intent.putExtra(INTENT_EXTRA_KEY_HEAD_PORTRAIT_URL, headPortraitUrl);
        intent.putExtra(INTENT_EXTRA_KEY_USER_ID, userId);
        return intent;
    }

    public static Intent getCallingIntent(Context context, String clientId, String headPortraitUrl, String userId, String nextTip) {
        Intent intent = getCallingIntent(context, clientId, headPortraitUrl, userId);
        intent.putExtra(INTENT_EXTRA_KEY_NEXT_TIP, nextTip);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_authentication);
        ButterKnife.bind(this);
        initActionBar();
        handleIntent();
        if (!checkArgs()) {
            finish();
            return;
        }
        initializeInjector();
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    @Override
    protected boolean shouldShowChatBall() {
        return false;
    }

    @Override
    protected boolean shouldProtectedByLockPattern() {
        return false;
    }

    private void handleIntent() {
        Intent intent = getIntent();
        mClientId = intent.getStringExtra(INTENT_EXTRA_KEY_CLIENT_ID);
        mHeadPortraitUrl = intent.getStringExtra(INTENT_EXTRA_KEY_HEAD_PORTRAIT_URL);
        mUserId = intent.getStringExtra(INTENT_EXTRA_KEY_USER_ID);
        mNextTip = intent.getStringExtra(INTENT_EXTRA_KEY_NEXT_TIP);
        NfsLog.d(TAG, "mClientId:" + mClientId);
        NfsLog.d(TAG, "mHeadPortraitUrl:" + mHeadPortraitUrl);
        NfsLog.d(TAG, "mUserId:" + mUserId);

    }

    private boolean checkArgs() {
        if (TextUtils.isEmpty(mClientId)) {
            return false;
        }
        if (TextUtils.isEmpty(mUserId)) {
            return false;
        }
        return true;
    }

    private void initializeInjector() {
        this.authenticationComponent = DaggerAuthenticationComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(getActivityModule())
                .authenticationModule(new AuthenticationModule(new ClientId(), new ClientSecret(), SecurityJNI.getAppSecret()))
                .build();
        this.authenticationComponent.inject(this);
    }

    private void initView() {
        initHeadPortrait();
        clientId.setText(PhoneNumberUtils.getPartHiddenNumber(mClientId));
        updateBtnNextState();

        ViewUtils.tintWidget(passwordEditText, android.R.color.white);
        passwordEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mClientSecret = s.toString();
                updateBtnNextState();
            }
        });
        updatePasswordIndicator(mClientSecretVisible);
    }

    private void initHeadPortrait() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_user_head_portrait_default)
                .showImageForEmptyUri(R.drawable.ic_user_head_portrait_default)
                .showImageOnFail(R.drawable.ic_user_head_portrait_default)
                .resetViewBeforeLoading(false)  // default
                .delayBeforeLoading(0)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
                .bitmapConfig(Bitmap.Config.ARGB_8888)              // default
                .displayer(new SimpleBitmapDisplayer()) // default 可以设置动画，比如圆角或者渐变
                .handler(new Handler())                             // default
                .build();

        ImageLoader.getInstance().displayImage(
                mHeadPortraitUrl,
                headPortrait,
                options);
    }

    private void updateBtnNextState() {
        if (TextUtils.isEmpty(mNextTip)) {
            btnNext.setText(R.string.next_prompt_default);
        } else {
            btnNext.setText(mNextTip);
        }
        btnNext.setEnabled(!TextUtils.isEmpty(mClientSecret));
    }

    @OnClick(R.id.btnNext)
    void onBtnNextClick() {
        NfsLog.d(TAG, "onBtnNextClick");
        if (authenticationPresenter != null) {
            NfsLog.d(TAG, "onBtnNextClick.000");
            initActionBar();
            authenticationPresenter.setView(this);
            authenticationPresenter.initialize();
            NfsLog.d(TAG, "onBtnNextClick.111");
        }
        NfsLog.d(TAG, "onBtnNextClick.222");
    }

    @OnClick(R.id.passwordIndicator)
    void onPasswordIndicatorClick() {
        mClientSecretVisible = !mClientSecretVisible;

        updatePasswordIndicator(mClientSecretVisible);

        EditTextUtils.setTextVisible(passwordEditText, mClientSecretVisible);
    }

    private void initActionBar() {
        enableLeftNavigationItem(true);
        setTitle(R.string.title_activity_authentication);
    }

    private void updatePasswordIndicator(boolean visible) {
        if (visible) {
            passwordIndicator.setImageResource(R.drawable.ic_password_indicator_visible);
        } else {
            passwordIndicator.setImageResource(R.drawable.ic_password_indicator_invisible);
        }
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

//            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
//            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
//                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
//                @Override
//                public void onAnimationEnd(Animator animation) {
//                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
//                }
//            });loginProgress.setVisibility(show ? View.VISIBLE : View.GONE);
            loginProgress.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    loginProgress.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            loginProgress.setVisibility(show ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void showLoading() {
        showProgress(true);
    }

    @Override
    public void hideLoading() {
        showProgress(false);
    }

    @Override
    public void onSuccess() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onError(String message) {
        ToastUtils.showShort(this, message);
    }

    @Override
    public Context getContext() {
        return this;
    }

}

